/**
 * 后台管理中根据用户名和标题进行关键字搜索
 */
const async = require('async');
module.exports = {
  open:false,
  description: '根据用户名和标题进行关键字搜索',
  handler(req,res,next){
    let doc = req.query;
    let filter = doc.filter||{};
    let sort = doc.sort||{createTime:-1};
    let search = filter.search||"";
    let page = doc.page;
    let skip = 0;
    let limit = 10;
    if(page){
      if(page.size){
        limit = page.size;
        if(page.index>1){
          skip = (page.index-1)*page.size;
        }
      }
    }
    async.auto([
          callback=>req.mongo.collection("card").aggregate([
            {
              $lookup:{
                from:"cardKind",
                localField:"cardKindID",
                foreignField:"_id",
                as:"cardKindID"
              }
            },
            {
              $unwind:"$cardKindID"
            },
            {
              $lookup:{
                from:"user",
                localField:"authorID",
                foreignField:"_id",
                as:"authorID"
              }
            },
            {$match:{$or:[{"authorID.nickname":{"$regex":search}},{"title":{"$regex":search}}]}},
            {$sort:sort},
            {
              $project:{
                _id:1,
                cardKind:"$cardKindID.kind",//起别名
                comment:1,
                picPath:1,
                soundPath:1,
                title:1,
                latitude:1,
                longitude:1,
                place:1,
                cardKindID:1,
                authorID:1,
                headPicPath:1,
                nickname:1,
                // careID:1,
                likeID:1,
                commentID:1,
                checkState:1,
                createTime:1
              }
            },
          ]).toArray(callback)
        ],
        (err, results) => {
          if (err) return res.err.mongoError(err);
          var card = results[0]||[];
          if (!page) {
            return res.reply(card);
          }
          let count = card.length;
          if (err) return res.err.mongoError(err);
          page.size = page.size || 10;
          page.index = page.index || 1;
          page.count = count;
          page.pageCount = Math.ceil(page.count / page.size);
          if(count<=0) return res.reply(page);
          page.hasPrevious = page.index > 1;
          page.hasNext = page.index < page.pageCount;
          page.index = page.pageCount < page.index ? page.pageCount : page.index;
          page.items = card.slice(skip,skip+limit);
          return res.reply({code:0,message:"查询成功",data:page});
        }
    )
  }
};
